/**
 * MIT License
 * Copyright (c) 2018 yadong.zhang
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.gkj.blog.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取IP的工具类
 */
public class IpUtil {
    private static final Logger LOGGER= LoggerFactory.getLogger(IpUtil.class);
    /**
     * 获取真实IP
     * @param request
     * @return
     */
    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        return checkIp(ip) ? ip : (
                checkIp(ip = request.getHeader("Proxy-Client-IP")) ? ip : (
                        checkIp(ip = request.getHeader("WL-Proxy-Client-IP")) ? ip :
                                request.getRemoteAddr()));
    }

    /**
     * 校验IP
     *
     * @param ip
     * @return
     */
    private static boolean checkIp(String ip) {
        return !StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip);
    }


    public static String getAddr(String ip){
        HttpURLConnection con = null;
        BufferedReader br = null;
        StringBuffer resultBuffer = null;
        try {
            URL url =new URL("https://api.map.baidu.com/location/ip?ak=msmALtk4G6NURryR8K74PrNsu2vvlKWw&coor=bd09ll&ip="+ip);
            con= (HttpURLConnection) url.openConnection();
            resultBuffer = new StringBuffer();
            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
            if (contentLength > 0) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
                String temp;
                while ((temp = br.readLine()) != null) {
                    resultBuffer.append(temp);
                }
            }
            String resp=resultBuffer.toString();
            Pattern re=Pattern.compile("\\|(.*?)\\|");
            Matcher matcher =re.matcher(resp);
            if(matcher.find()){
                String addrU=matcher.group(1);
                StringBuilder addr=new StringBuilder();
                String[] arr=addrU.split("\\\\u");
                for(int i=1;i<arr.length;i++){
                    int charData = Integer.parseInt(arr[i], 16);
                    addr.append((char) charData);
                }
                return addr.toString();
            }
            else{
                LOGGER.error("获取{}归属地失败",ip);
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("获取{}归属地失败",ip);
        }
        return null;
    }
}